﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Configuration;
using System.Text.RegularExpressions;

namespace SMSTester.Controls
{
    public partial class DataGenerator : UserControl
    {
        #region Consts
        public const string cApplicationRegistryPath = "HKEY_CURRENT_USER\\Software\\SMSTester";
        #endregion

        #region Fields
        public string TableNameMessage = string.Empty;
        public string TableNameMessageBody = string.Empty;
        public static Random RandomNumber = new Random(DateTime.Now.Millisecond);
        private DataTable MessageTable = null;
        #endregion

        #region Properties
        #endregion

        #region Initialization
        public DataGenerator()
        {
            InitializeComponent();
        }
        #endregion

        #region Events
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            using (new CursorWait())
            {
                int locInsertedRecords = 0;
                int locInsertedRecordsError = 0;
                progressBar.Visible = true;
                progressBar.Properties.Minimum = 0;
                progressBar.Properties.Maximum = Convert.ToInt32(
                        seMessagesCount.Value * seRecipientsForMessage.Value);
                progressBar.Position = 0;


                for (int locMessageBodyIndex = 0; locMessageBodyIndex < seMessagesCount.Value; locMessageBodyIndex++)
                {

                    string locQueryBody = @"
INSERT INTO [" + TableNameMessageBody + @"]
       ([Body]
       ,[IsUnicode]
       ,[Subject])
OUTPUT Inserted.BodyID
VALUES
       ('@Body@'
       ,'True'
       ,'')
                    ".Replace(
                        "@Body@",
                        GetStr(txtMessage.Text).Replace("'", "''")
                    );

                    try
                    {
                        // Insert body
                        int locBodyID = SQLConnect.Instance.ExecuteNonQueryReturnIdentity(locQueryBody);
                        locInsertedRecords++;

                        for (int locMessageIndex = 0; locMessageIndex < seRecipientsForMessage.Value; locMessageIndex++)
                        {
                            string locQuery = @"
INSERT INTO [" + TableNameMessage + @"]
       ([Sender]
       ,[Recipient]
       ,[BodyID])
OUTPUT Inserted.MessageID
VALUES
       ('@Sender@'
       ,'@Recipient@'
       ,@BodyID@)
                        ".Replace(
                                "@Sender@",
                                GetStr(txtFrom.Text).Replace("'", "''")
                            ).Replace(
                                "@Recipient@",
                                GetStr(txtTo.Text).Replace("'", "''")
                            ).Replace(
                                "@BodyID@",
                                locBodyID.ToString()
                            );

                            // Insert message header
                            try
                            {
                                locInsertedRecords++;
                                int locMessageID = SQLConnect.Instance.ExecuteNonQueryReturnIdentity(locQuery);
                            }
                            catch
                            {
                                locInsertedRecordsError++;
                            }

                            if (progressBar.Position < progressBar.Properties.Maximum - 1)
                                progressBar.Position++;
                            progressBar.Refresh();

                        }
                    }
                    catch
                    {
                        locInsertedRecordsError++;
                    }

                }
                MessageBox.Show(
                    "Inserted " + locInsertedRecords.ToString() +
                    " records\r\n Errors: " + locInsertedRecordsError.ToString());
            }
            progressBar.Visible = false;
            MessageTable = null;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            using (new CursorWait())
            {
                SQLConnect.Instance.ExecuteNonQuery("delete from " + TableNameMessage);
                SQLConnect.Instance.ExecuteNonQuery("delete from " + TableNameMessageBody);
                MessageTable = null;
            }
        }
        
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            using (new CursorWait())
            {
                MessageTable = SQLConnect.Instance.Select(
                    @"
select  
	body.BodyID
	,body.Body
	,body.IsUnicode
	,body.Subject
	,mess.MessageID
	,mess.Sender
	,mess.Recipient
  FROM " + TableNameMessageBody + @" body
  left join " + TableNameMessage + @" mess on mess.BodyID = body.BodyID
                    ",
                    new List<KeyValuePair<string, Type>>()
                    {
	                    { new KeyValuePair<string,Type>("BodyID", typeof(int))},
	                    { new KeyValuePair<string,Type>("Body", typeof(string))},
	                    { new KeyValuePair<string,Type>("IsUnicode", typeof(bool))},
	                    { new KeyValuePair<string,Type>("Subject", typeof(string))},
	                    { new KeyValuePair<string,Type>("MessageID", typeof(int))},
	                    { new KeyValuePair<string,Type>("Sender", typeof(string))},
	                    { new KeyValuePair<string,Type>("Recipient", typeof(string))}
                    }
                    );

                bindingSource1.DataSource = MessageTable;

            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            using (new CursorWait())
            {
                progressBar.Visible = true;
                progressBar.Properties.Minimum = 0;
                progressBar.Properties.Maximum = MessageTable.Rows.Count;
                progressBar.Position = 0;

                foreach (DataRow dr in MessageTable.Rows)
                {
                    if (dr.RowState == DataRowState.Modified)
                    {

                        // update message body
                        SQLConnect.Instance.ExecuteNonQuery(
                            @"
UPDATE [" + TableNameMessageBody + @"]
SET [Body] = '@Body@'
   ,[IsUnicode] = '@IsUnicode@'
   ,[Subject] = '@Subject@'
WHERE BodyID = @BodyID@  
                        ".Replace(
                                "@Body@",
                                Convert.ToString(dr["Body"]).Replace("'", "''")
                            ).Replace(
                                "@Subject@",
                                Convert.ToString(dr["Subject"]).Replace("'", "''")
                            ).Replace(
                                "@BodyID@",
                                Convert.ToString(dr["BodyID"]).Replace("'", "''")
                            ).Replace(
                                "@IsUnicode@",
                                (Convert.ToBoolean(dr["IsUnicode"]) ? "True" : "False")
                            )
                         );


                        // update message header
                        SQLConnect.Instance.ExecuteNonQuery(
                            @"
UPDATE [" + TableNameMessage + @"]
   SET [Sender] = '@Sender@'
      ,[Recipient] = '@Recipient@'
WHERE MessageID = @MessageID@  
                        ".Replace(
                                "@Sender@",
                                Convert.ToString(dr["Sender"]).Replace("'", "''")
                            ).Replace(
                                "@Recipient@",
                                Convert.ToString(dr["Recipient"]).Replace("'", "''")
                            ).Replace(
                                "@MessageID@",
                                Convert.ToString(dr["MessageID"]).Replace("'", "''")
                            )
                          );



                    } // if modify
                    if (progressBar.Position < progressBar.Properties.Maximum - 1)
                        progressBar.Position++;
                    progressBar.Refresh();
                }
                progressBar.Visible = false;
            }
        }
        #endregion

        #region Methods
        public void Init(bool paramVisible)
        {
            this.Visible = paramVisible;
            if (paramVisible)
            {
                this.Dock = DockStyle.Fill;
            }
        }

        public void GetParams()
        {
            int i;

            try
            {
                if (Int32.TryParse(
                        Microsoft.Win32.Registry.GetValue(
                            cApplicationRegistryPath,
                            this.Name + "MessagesCount",
                            seMessagesCount.Value
                            ).ToString(), out i))
                    seMessagesCount.Value = i;

                if (Int32.TryParse(
                        Microsoft.Win32.Registry.GetValue(
                            cApplicationRegistryPath,
                            this.Name + "RecipientsForMessage",
                            seRecipientsForMessage.Value
                            ).ToString(), out i))
                    seRecipientsForMessage.Value = i;

                txtFrom.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "From",
                           txtFrom.Text
                           ).ToString();

                txtTo.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "To",
                           txtTo.Text
                           ).ToString();

                txtMessage.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "Message",
                           txtMessage.Text
                           ).ToString();

                txtSymbols.Text = Microsoft.Win32.Registry.GetValue(
                           cApplicationRegistryPath,
                           this.Name + "Symbols",
                           txtSymbols.Text
                           ).ToString();
            }
            catch { }
        }

        public void SetParams()
        {
            Microsoft.Win32.Registry.SetValue(
                cApplicationRegistryPath,
                this.Name + "MessagesCount",
                Convert.ToInt32(seMessagesCount.Value).ToString()
                );

            Microsoft.Win32.Registry.SetValue(
                cApplicationRegistryPath,
                this.Name + "RecipientsForMessage",
                Convert.ToInt32(seRecipientsForMessage.Value).ToString()
                );

            Microsoft.Win32.Registry.SetValue(
                   cApplicationRegistryPath,
                   this.Name + "From",
                   txtFrom.Text
                   );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "To",
                       txtTo.Text
                       );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "Message",
                       txtMessage.Text
                       );

            Microsoft.Win32.Registry.SetValue(
                       cApplicationRegistryPath,
                       this.Name + "Symbols",
                       txtSymbols.Text
                       );

        }

        private string GetStr(string paramString)
        {
            string locResult = paramString;
            string locChars = txtSymbols.Text;

            Regex r;
            Match m;

            // chars %123% = char with ascii code=123
            r = new Regex(
                    "(%[0-9]+)",
                    RegexOptions.IgnoreCase | RegexOptions.Compiled);
            for (m = r.Match(paramString); m.Success; m = m.NextMatch())
            {
                string str = m.Groups[1].ToString().Replace("%", "");
                int locNum = Int32.Parse(str);
                locChars = new Regex(
                    m.Groups[1].ToString(),
                    RegexOptions.IgnoreCase | RegexOptions.Compiled
                    ).Replace(
                        locChars,
                        Convert.ToChar(locNum).ToString()
                        );
            }

            // Message (%3-6% = random string, length from 3 to 6)
            r = new Regex(
                    "(%[0-9]+\\-[0-9]+%)",
                    RegexOptions.IgnoreCase | RegexOptions.Compiled);
            for (m = r.Match(paramString); m.Success; m = m.NextMatch())
            {
                string str = m.Groups[1].ToString().Replace("%", "");
                int locPosOfMinusChar = str.IndexOf("-");
                string locNumFromStr = str.Substring(0, locPosOfMinusChar);
                string locNumToStr = str.Substring(locPosOfMinusChar + 1);
                int locNumFrom = Int32.Parse(locNumFromStr);
                int locNumTo = Int32.Parse(locNumToStr);

                String locRandomString = "";
                for (int i = 0; i < DataGenerator.RandomNumber.Next(locNumFrom, locNumTo); i++)
                    locRandomString += locChars[DataGenerator.RandomNumber.Next(locChars.Length)];

                locResult = new Regex(
                    m.Groups[1].ToString(),
                    RegexOptions.IgnoreCase | RegexOptions.Compiled
                    ).Replace(
                        locResult,
                        locRandomString
                        );
            }


            // Message (%N3-6% = random number)
            r = new Regex(
                    "(%N[0-9]+\\-[0-9]+%)",
                    RegexOptions.IgnoreCase | RegexOptions.Compiled);
            for (m = r.Match(paramString); m.Success; m = m.NextMatch())
            {
                string str = m.Groups[1].ToString().Replace("%", "").Replace("N", "");
                int locPosOfMinusChar = str.IndexOf("-");
                string locNumFromStr = str.Substring(0, locPosOfMinusChar);
                string locNumToStr = str.Substring(locPosOfMinusChar + 1);
                int locNumFrom = Int32.Parse(locNumFromStr);
                int locNumTo = Int32.Parse(locNumToStr);

                String locRandomString = "";
                for (int i = 0; i < DataGenerator.RandomNumber.Next(locNumFrom, locNumTo); i++)
                    locRandomString += DataGenerator.RandomNumber.Next(10).ToString();

                locResult = new Regex(
                    m.Groups[1].ToString(),
                    RegexOptions.IgnoreCase | RegexOptions.Compiled
                    ).Replace(
                        locResult,
                        locRandomString
                        );
            }

            return locResult;
        }
        #endregion


    }
}
